package com.sgffsg.learn.javalib.thread;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: lmk
 * @date: 2024/3/31
 * @desc: 生产者消费者模型Object实现
 */
public class ProducerConsumerModel1 {

    static Object object = new Object();
    private static final int MAX = 5;

    static List<String> products = new ArrayList<String>();

    static class Producer extends Thread {

        Producer(String name) {
            setName(name);
        }

        @Override
        public void run() {
            synchronized (object) {
                while (true) {
                    if (products.size() < MAX) {
                        String product = "编号：" + System.currentTimeMillis();
                        products.add(product);
                        System.out.println(Thread.currentThread().getName() + "生产了产品-" + product);
                        try {
                            Thread.sleep(2000L);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        object.notify();
                    } else {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }

    static class Consumer extends Thread {

        Consumer(String name) {
            setName(name);
        }

        @Override
        public void run() {
            synchronized (object) {
                while (true) {
                    if (products.size() > 0) {
                        String product = products.get(0);
                        products.remove(0);
                        System.out.println(Thread.currentThread().getName()+"消费了产品-" + product);
                        try {
                            Thread.sleep(2000L);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        object.notify();
                    } else {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }


    public static void main(String[] args) {
        System.out.println("Starting-------");
        for (int i = 0; i < 3; i++) {
            Producer p = new Producer("Producer" + i);
            Consumer c = new Consumer("Consumer" + i);
            p.start();
            c.start();
        }
        System.out.println("Starting-------end-------");
    }
}
